package cn.chencaiju.exam;

import java.util.Arrays;

import org.junit.Test;

public class ArrayCombine {
	public static int[] merge(int[] a1, int[] a2) {
		int len1=a1.length;
		int len2=a2.length;
		int[] combine=new int[len1+len2];
		for(int i=0;i<len1;i++) {
			combine[i]=a1[i];
		}
		for(int i=0;i<len2;i++) {
			combine[len1++]=a2[i];
		}
		Arrays.sort(combine);
		return combine;
	}
	public int[] merge2(int[] a1,int[] a2) {
		int len1=a1.length;
		int len2=a2.length;
		int i1=0,i2=0,i=0;
		int[] combine=new int[len1+len2];
		while(i<len1+len2) {
			if(i1<len1&&i2<len2) {
				if(a1[i1]>a2[i2]) {
					combine[i++]=a2[i2++];
				}else {
					combine[i++]=a1[i1++];
				}
			}else {
				if(i1>=len1&&i2<len2) {
					combine[i++]=a2[i2++];
					continue;
				}
				if(i2>=len2&&i1<len1) {
					combine[i++]=a1[i1++];
					continue;
				}
			}
			
		}
		return combine;
	}
	@Test public void testMerge() {
		for(int i=0;i<100;i++) {
			int rang=(int) (Math.random()*9+1);
			int[] a1=new int[rang];
			int[] a2= new int[rang];
			for(int j=0;j<rang;j++) {
				a1[j]=(int) (Math.random()*99+1);
				a2[j]=(int) (Math.random()*99+1);
			}
			Arrays.sort(a1);
			Arrays.sort(a2);
			System.out.println(Arrays.toString(merge(a1,a2)));
			System.out.println(Arrays.toString(merge2(a1,a2)));
			System.out.println();
			}
	}
}
